package studio.xiaoyun.core.xstream;

import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.converters.collections.ArrayConverter;
import com.thoughtworks.xstream.core.util.HierarchicalStreams;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.mapper.Mapper;

/**
 * 用于array和xml之间的转换，可以自定义数组节点的名称
 */
public class NamedArrayConverter extends ArrayConverter {
    private final Mapper mapper;
    private final String name;

    /**
     *
     * @param mapper mapper
     * @param name 数组节点的名称
     */
    public NamedArrayConverter(Mapper mapper,String name) {
        super(mapper);
        this.mapper = mapper;
        this.name = name;
    }

    @Override
    protected void writeItem(Object item, MarshallingContext context, HierarchicalStreamWriter writer) {
        writer.startNode(name);
        writer.addAttribute(mapper.aliasForSystemAttribute("class"), mapper.serializedClass(item.getClass()));
        context.convertAnother(item);
        writer.endNode();
    }

    @Override
    protected Object readItem(HierarchicalStreamReader reader, UnmarshallingContext context, Object current) {
        String className = HierarchicalStreams.readClassAttribute(reader, mapper);
        Class itemType = mapper.realClass(className);
        return context.convertAnother(null, itemType);
    }
}
